package vkplayer.logic;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import vkplayer.common.Constant;
import vkplayer.exceptions.PropertiesLoadException;

public class PropertiesLoader {

    public Map<String, String> getProperties() throws PropertiesLoadException {
        Properties properties = loadProperties(Constant.pathConfigFile);
        return transofmProperties(properties);
    }

    public void saveProperties(Map<String, String> data) {
        Properties prop = new Properties();
        prop.putAll(data);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(Constant.pathConfigFile);
        } catch (FileNotFoundException e) {
            Logger.getLogger(PropertiesLoader.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            prop.store(outputStream, null);
        } catch (IOException e) {
            Logger.getLogger(PropertiesLoader.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                Logger.getLogger(PropertiesLoader.class.getName()).log(Level.SEVERE, null, e);
            }
        }

    }

    private Map<String, String> transofmProperties(Properties properties)
            throws PropertiesLoadException {
        Map<String, String> data = new HashMap<String, String>();
        data.put(Constant.EMAIL, properties.getProperty(Constant.EMAIL));
        data.put(Constant.PASS, properties.getProperty(Constant.PASS));
        return data;

    }

    private Properties loadProperties(String pathFile)
            throws PropertiesLoadException {
        Properties prop = new Properties();
        InputStream inputStream;
        try {
            inputStream = new FileInputStream(pathFile);
        } catch (FileNotFoundException e) {
            throw new PropertiesLoadException(e);
        }
        try {
            prop.load(inputStream);
        } catch (IOException e) {
            throw new PropertiesLoadException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.getLogger(PropertiesLoader.class.getName()).log(Level.SEVERE, null, e);
            }
        }
        return prop;

    }
}
